<template>
  <div>
    <el-container class="container-box">
      <el-main class="container-content">
        <div>
          <div class="match-search-btn">
            <el-button size="default" type="primary" @click="start">刷新</el-button>
            <router-link v-slot="{ navigate }" custom :to="{ name: '创建比赛', params: { ID: teamId }, }">
              <el-button size="default" :style="{ '--el-button-hover-color': 'var(--color-cheng2)', }" type="primary"
                @click="navigate">创建比赛</el-button>
            </router-link>
          </div>
          <el-table class="match-list-table" height="80vh" row-class-name="cursor-pointer" :data="activityData"
            @row-click="clickTableRow" style="width: 100%" size="">
            <template v-slot:empty>
              <el-empty image="https://cdn-hterobot.oss-cn-qingdao.aliyuncs.com/image/ojSass-empty.png" />
            </template>
            <el-table-column prop="date" label="状态" width="90">
              <template #default="{ row }">
                <el-tag :type="jianchatime(row, datenow).type" effect="dark" size="default">
                  {{ jianchatime(row, datenow).text2 }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="ID" sortable label="id" width="80"></el-table-column>
            <el-table-column prop="userid" sortable label="创建者" width="120">
              <template #default="scope">
                {{ scope.row.user?.name }}
              </template>
            </el-table-column>
            <el-table-column prop="name" label="比赛名" width=""></el-table-column>
            <el-table-column prop="type" label="类型" width="80">
              <template #default="{ row }">
                {{ row.type === "public" ? "公开" : "非公开" }}
              </template>
            </el-table-column>
            <el-table-column prop="format" label="赛制" width="80">
            </el-table-column>
            <el-table-column prop="date" label="时间" show-overflow-tooltip width="">
              <template #default="{ row }">
                {{ TimeYH1(row.activitystarttime) }}
                -
                {{ TimeYH1(row.activityendtime) }}
              </template>
            </el-table-column>
            <el-table-column prop="matchuserquestioncount" label="提交人数" width="90"></el-table-column>
            <el-table-column prop="date" label="时长" width="100" :formatter="formatterDuration"></el-table-column>
            <!-- <el-table-column prop="date" label="计时方式" width="">
              <template #default="{ row }">
                {{ row.duration ? '个人计时' : '统一计时' }}
              </template>
            </el-table-column> -->
            <!-- 操作 -->
            <el-table-column label="操作" fixed="right" width="360">
              <template #default="{ row }">
                <router-link v-slot="{ navigate }" custom
                  :to="{ name: '创建比赛', params: { ID: teamId }, query: { ID: row.ID } }">
                  <el-button size="default" type="primary" @click.stop="navigate">修改</el-button>
                </router-link>
                <el-button size="default" type="danger" @click.stop="delactivity(row.ID)">删除</el-button>
                <el-button size="default" type="info" @click.stop="copyMatch(row.ID)">复制</el-button>
                <el-dropdown style="margin-left:12px" trigger="click">
                  <el-button size="default" type="primary" @click.stop>
                    更多操作<el-icon class="el-icon--right"><arrow-down /></el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item>
                        <el-button type="info" plain size="default" @click="savePDF(row)">保存比赛为PDF </el-button>
                      </el-dropdown-item>
                      <el-dropdown-item>
                        <el-button type="info" plain size="default" @click="downloadcode(row)">下载提交的代码 </el-button>
                      </el-dropdown-item>
                      <el-dropdown-item>
                        <el-button type="info" plain size="default" @click="_downloadmatchquestion(row)">下载比赛的题目
                        </el-button>
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页 -->
          <el-pagination class="pager" :page-size="limit" :total="totalCount" @current-change="changePage"
            layout="total,prev, pager, next" :current-page="Math.floor(offset / limit) + 1">
          </el-pagination>
        </div>
      </el-main>
    </el-container>


  </div>
</template>
<script setup lang="ts">
import { ElMessage, ElMessageBox } from "element-plus";
import { saveAs } from 'file-saver';
import jszip from 'jszip';
import { debounce } from "underscore";
import { computed, onMounted, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useStore } from "vuex";
import { asyncTeamCopyActivity, asyncTeamSelectActivity, asyncgetusermatchcode, asyncteamdelactivity } from "../../../api";
import { Storekey } from "../../../interface";
import Studycodemodel from "../../../mysql_interface/studycodemodel";
import { TimeYH1, } from "../../../util/time";
import { downloadmatchquestion } from "../../../util/updateoss";
import { jianchatime } from "@/util/jianchatime";

// 赛制
enum Format {
  OI = "OI",
  IOI = "IOI",
}
const route = useRoute()
const router = useRouter()
const store = useStore(Storekey)
const user = computed(() => {
  return store.state.user
})
const teamId = computed(() => {
  return user.value?.teamid;
});

const datenow = computed(() => {
  return store.state.time
})

// 搜索条件
const offset = ref(Number(route.query.offset) || 0)
const order = computed(() => {
  return route.query.order as string
})
const limit = computed(() => {
  return Number(route.query.limit) || 20
})

const activityData = ref<Studycodemodel.Iactivity[]>([])
const totalCount = ref<number>(0)
onMounted(() => {
  start()
})
const debouncet1 = ref(debouncet())
function start() {
  debouncet1.value()
}
function debouncet() {
  return debounce(async () => {
    const { rows, count } = await asyncTeamSelectActivity({
      teamid: teamId.value,
      _limit: limit.value,
      _offset: offset.value,
    })
    activityData.value = rows
    totalCount.value = count
  }, 300);
}
function changePage(r: number) {
  offset.value = (r - 1) * limit.value
}
// 表格点击行
const selectedRow = ref<Studycodemodel.Iactivity>();
function clickTableRow(row: Studycodemodel.Iactivity, column: any, event: Event): void {
  selectedRow.value = row
  router.push({ name: "查看比赛", params: { ID: row.ID } });
}
// formatter
function time(a: Date, b: Date) {
  const t = new Date(b).getTime() - new Date(a).getTime()
  let n: string | number = (t / 60 / 60 / 1000).toFixed(1)
  if (Number(n) === Math.floor(Number(n))) {
    n = Math.floor(Number(n))
  }
  return n + '小时'
}
function formatterDuration(row: Studycodemodel.Iactivity) {
  return row.duration ?
    `${(row.duration / 60).toFixed(1)}小时` :
    time(row?.activitystarttime, row?.activityendtime)
}

// 删除
function delactivity(id?: number) {
  if (id) {
    ElMessageBox.confirm("是否删除该比赛, 是否继续?", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(async () => {
        await asyncteamdelactivity({ ID: id, teamid: teamId.value });
        ElMessage({
          type: "success",
          message: "删除成功!",
        });
        start();
      })
      .catch(() => {
        ElMessage({
          type: "info",
          message: "已取消删除",
        });
      });
  }
}
// 复制
function copyMatch(ID?: number) {
  if (ID) {
    try {
      ElMessageBox.confirm("是否复制该比赛, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          await asyncTeamCopyActivity({ ID, teamid: teamId.value });
          ElMessage({
            type: "success",
            message: "复制成功!",
          });
          start();
        })
        .catch(() => {
          ElMessage({
            type: "info",
            message: "已取消复制",
          });
        });
    } catch (e: any) {
      ElMessage({
        message: "复制失败" + e,
        type: "error",
      });
    }
  }
}
// 
function savePDF(row: Studycodemodel.Iactivity) {
  // <a target="_blank" :href="`/question.html?activityid=${row.ID}&title=${row.name}`"></a>
  const { origin, pathname } = window.location;
  window.open(`${origin}/question.html?activityid=${row.ID}&title=${row.name}`)
}

// 
function downloadcode(row: Studycodemodel.Iactivity) {
  asyncgetusermatchcode({ activityid: row.ID }).then(data => {
    const zip = new jszip()
    data.forEach(a => {
      zip.file(a[0], a[1])
    })
    zip.generateAsync({ type: "blob" }).then(e => {
      console.log(e)
      saveAs(e, '代码.zip')
    })
  }).catch(e => {
    ElMessage.error(e)
  })
}
// 
const loading = ref(false)
async function _downloadmatchquestion(row: Studycodemodel.Iactivity) {
  loading.value = true
  downloadmatchquestion({ data: row }, true)
  loading.value = false
}


</script>

<style scoped>
.container-box {
  /* padding: var(--container-margin) 5% 0;
  margin: var(--container-margin) 0rem 0 0rem; */
  /* 外边距 */
  --container-margin: 20px;
  --container-header-height: 10vh;
  --container-bg-color: #fff;
}

.container-header {
  height: var(--container-header-height);
  min-height: var(--container-header-height);
  background: var(--container-bg-color);
  width: 100%;
  padding: 0;
}

.container-content {
  background: var(--container-bg-color);
  padding: 0;
  min-width: 100%;
}

.container-content .pager {
  margin-top: var(--container-margin);
  float: right;
}

.match-search-btn {
  margin-bottom: var(--container-margin);
}

.match-list-table {
  margin-top: var(--container-margin);
}

/* 状态 */
.info,
.primary,
.danger,
.success {
  width: 44px;
  height: 24px;
  color: #fff;
  display: inline-block;
  text-align: justify;
  font-size: 12px;
  font-weight: 400;
  line-height: 24px;
  text-align: center;
  border-radius: 5px;
}

/* 赛事结束-已结束 */
.info {
  background-color: rgba(236, 128, 141, 1);
}

/* 立即报名-报名中 */
.primary {
  background: rgb(112, 182, 3);
  /* transform: translateY(-3px); */
}

/* 即将开赛-未开始 */
.danger {
  background: rgb(170, 170, 170);
  /* transform: translateY(-3px); */
}

/* 进入比赛-比赛中 */
.success {
  background: var(--color-cheng);
  /* transform: translateY(-3px); */
}
</style>

<style>
.ojSass .container-content .table-header {
  font-weight: ;
}
</style>